<template>
  <div class="app-container">
    <Form
      v-if="showSearch"
      v-model:formData="searchInfo"
      :formItems="formItems"
    >
      <template #footer>
        <div style="text-align: left">
          <el-button size="small" icon="Search" type="primary" @click="goSearch"
            >搜索</el-button
          >
          <el-button size="small" icon="Refresh" @click="resetSearch"
            >重置</el-button
          >
        </div>
      </template>
    </Form>
    <h3></h3>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"> </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="resetSearch"
      ></right-toolbar>
    </el-row>
    <!-- <h3>订单操作只能针对商户自己的渠道,平台产品订单无法修改</h3> -->
    <h3>
      <el-button
        type="primary"
        icon="Download"
        @click="exportOrder"
        size="small"
        v-hasPermi="['member:order:exportUserOrderList']"
        >导出</el-button
      >
      <el-button
        type="danger"
        icon="Edit"
        @click="handleRefund"
        size="small"
        :disabled="multiple"
        v-hasPermi="['member:order:handleRefund']"
        >批量退款</el-button
      >
      <!-- <el-button
        type="info"
        icon="Edit"
        plain
        @click="orderResubmit"
        size="small"
        :disabled="!checkList.length"
        v-hasPermi="['member:order:orderReSubmit']"
        >重提订单</el-button
      >
      <el-button
        type="warning"
        icon="Edit"
        plain
        @click="changeAuto(0)"
        size="small"
        :disabled="!checkList.length"
        v-hasPermi="['member:order:updateOrderProcessType']"
        >手动处理</el-button
      >
      <el-button
        type="success"
        icon="Edit"
        plain
        :disabled="!checkList.length"
        @click="changeAuto(1)"
        size="small"
        v-hasPermi="['member:order:updateOrderProcessType']"
        >自动处理</el-button
      >
      <el-button
        type="primary"
        icon="Edit"
        plain
        :disabled="!checkList.length"
        @click="changeStatus"
        size="small"
        v-hasPermi="['member:order:changeStatus']"
        >批量修改状态</el-button
      > -->
      <!-- changeStatus -->
    </h3>
    <x-table
      :propList="propList"
      :tableData="info.items"
      :isLoading="isLoading"
      isShowCheckBox
      @selection-change="selectionChange"
      firstIsFixed
      isShowExpand
      :isBorder="false"
    >
      <template #expand="props">
        <!-- -->
        <el-form label-position="left" inline class="demo-table-expand">
          <!-- <el-form-item label="用户是否支付" label-width="120px">
            <span v-if="props.row.pay_status == 1">已支付</span>
            <span v-if="props.row.pay_status == 0">未支付</span>
          </el-form-item> -->
          <el-form-item label="平台订单状态" label-width="120px">
            <span v-if="props.row.plat_status == 1">未扣款</span>
            <span v-if="props.row.plat_status == 2">已扣款</span>
            <span v-if="props.row.plat_status == 3">已退款</span>
          </el-form-item>

          <!-- <el-form-item label="成本（自建渠道才存在）" label-width="200px">
            <span>{{ props.row.const_price }}</span>
          </el-form-item> -->

          <!-- <el-form-item label="采购价">
            <span>{{ props.row.user_price }}</span>
          </el-form-item> -->
          <el-form-item label="凭证">
            <span>{{ props.row.voucher }}</span>
          </el-form-item>
          <el-form-item label="分佣" label-width="120px">
            <span>{{ props.row.commission?.name }}</span>
          </el-form-item>
          <el-form-item label="直/间推粉丝收益" label-width="120px">
            <span
              >{{ props.row.commission_money1 }}/{{
                props.row.commission_money2
              }}</span
            >
          </el-form-item>

          <el-form-item label="备注">
            <span>{{ props.row.remark }}</span>
          </el-form-item>
          <!-- <el-form-item label="操作描述">
            <span>{{ props.row.act_remark }}</span>
          </el-form-item> -->
        </el-form>
      </template>
      <template #order_status="{ row }">
        <el-tag v-if="row.order_status == 3" type="success">充值成功</el-tag>
        <el-tag v-if="row.order_status == 4" type="danger">充值失败</el-tag>
        <el-tag v-if="row.order_status == 2" type="info">充值中</el-tag>
        <el-tag v-if="row.order_status == 1">下单成功</el-tag>
        <el-tag v-if="row.order_status == 5" type="warning">压单</el-tag>
        <el-tag v-if="row.order_status == 6" type="warning">失败拦截</el-tag>
      </template>
      <template #refund_status="{ row }">
        <el-tag v-if="row.refund_status == 2" type="success">退款成功</el-tag>
        <el-tag v-if="row.refund_status == 3" type="danger">退款失败</el-tag>
        <el-tag v-if="row.refund_status == 1" type="info">退款中</el-tag>
        <el-tag v-if="row.refund_status == 0">未退款</el-tag>
      </template>

      <template #payment="{ row }">
        <el-tag type="success">{{ row.pay?.payment_name || "无" }}</el-tag>
      </template>
      <template #is_auto="{ row }">
        <el-tag v-if="row.is_auto == 1" type="success">自动</el-tag>
        <el-tag v-if="row.is_auto == 0" type="warning">手动</el-tag>
      </template>
      <template #area="scope">
        <span>{{ scope.row.area_name }}</span>
        <div v-if="scope.row.isp == 1">移动</div>
        <div v-if="scope.row.isp == 2">联通</div>
        <div v-if="scope.row.isp == 3">电信</div>
      </template>

      <template #pay_status="{ row }">
        <el-tag v-if="row.pay_status == 1" type="success">已支付</el-tag>
        <el-tag v-else type="info">未支付</el-tag>
      </template>
      <template #plat_status="{ row }">
        <el-tag v-if="row.plat_status == 2" type="success">已扣款</el-tag>
        <el-tag v-if="row.plat_status == 1">未扣款</el-tag>
        <el-tag v-if="row.plat_status == 3" type="success">已退款</el-tag>
      </template>
      <template #commission_status="{ row }">
        <el-tag v-if="row.commission_status == 1" type="success">已完成</el-tag>
        <el-tag v-else>未完成</el-tag>
      </template>
      <template #created_at="scope">
        <span>{{ scope.row.created_at }}</span>
        <br />
        <span>{{ scope.row.updated_at }}</span>
      </template>
      <template #sale_price="scope">
        <el-tag type="warning">{{ scope.row.sale_price }}</el-tag>
        <br />
        <el-tag type="success">{{ scope.row.user_price }}</el-tag>
      </template>

      <template #op="{ row }">
        <el-button
          v-if="
            (row.refund_status == 0 || row.refund_status == 3) &&
            row.pay_status == 1
          "
          type="primary"
          link
          icon="Position"
          @click="refund(row)"
          v-hasPermi="['member:order:refund']"
          >退款</el-button
        >
        <!-- <el-button type="primary"
link icon="Delete" @click="del(row)">删除</el-button> -->
      </template>
    </x-table>
    <pagination
      v-show="info.total > 0"
      :total="info.total"
      v-model:page="searchInfo.pageNum"
      v-model:limit="searchInfo.pageSize"
      @pagination="getInfo"
    />
    <Dialog
      width="30%"
      :title="dialogConfig.title"
      v-model:isShowDialog="isShowDialog"
      :isLoading="isSubmitLoading"
      @confirm="submit"
    >
      <Form ref="formRef" v-bind="dialogConfig.formConfig"> </Form>
    </Dialog>
    <el-dialog
      title="批量改状态"
      v-model="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="已选择数量">
          {{ checkList.length }}
        </el-form-item>
        <el-form-item label="温馨提示">
          <span style="color: red"
            >请确保没有勾选错订单以及要更改的订单状态!！！</span
          >
        </el-form-item>
        <el-form-item label="修改状态" prop="order_status">
          <el-radio-group v-model="form.order_status">
            <el-radio-button :label="2">充值中</el-radio-button>
            <el-radio-button :label="3">充值完成</el-radio-button>
            <el-radio-button :label="4">充值失败</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="密码"
          v-if="form.order_status == 4"
          prop="password"
        >
          <el-input
            v-model="form.password"
            placeholder="请输入登录密码确认操作"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="loading2" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :title="title2"
      v-model="open2"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="100px">
        <el-form-item label="已选择数量">
          {{ checkList.length }}
        </el-form-item>

        <el-form-item label="变更渠道" prop="change_channel">
          <el-radio-group v-model="form2.change_channel">
            <el-radio-button :label="0">不变更</el-radio-button>
            <el-radio-button :label="1">变更渠道</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="密码"
          v-if="form2.change_channel == 1"
          prop="password"
        >
          <el-input
            v-model="form2.password"
            placeholder="请输入登录密码确认操作"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="温馨提示" v-if="form2.change_channel == 1">
          <span style="color: red"
            >请确认不要选错渠道，否则损失自负。请确认已提前添加好渠道产品，否则重提会失败。</span
          >
        </el-form-item>
        <el-form-item
          label="渠道"
          prop="channel_id"
          v-if="form2.change_channel == 1"
        >
          <el-select
            v-model="form2.channel_id"
            placeholder="请选择渠道"
            filterable
            clearable
          >
            <el-option
              v-for="channel in channelList"
              :key="channel.id"
              :label="channel.channel_name"
              :value="channel.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="loading2" type="primary" @click="submitForm2"
            >确 定</el-button
          >
          <el-button @click="loading2 = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { propList, formItems, dialogConfig, sendThis } from "./config";
import {
  getList,
  refund,
  changeStatus,
  updateOrderProcessType,
  orderReSubmit,
} from "@/api/member/order";
import { getArea } from "@/api/common";
import { getAllList as getAllSpec } from "@/api/member/productSpec";
import { getPayAllList } from "@/api/member/paySet";

import { getSysCateList as getAllCateList } from "@/api/member/productCate";
import { getAllChannel as listAllChannel } from "@/api/member/channel";

export default {
  name: "merchantorderindex",
  data() {
    return {
      openRefund: false,
      formRefund: {
        remark: undefined,
        password: undefined,
      },
      formRefundRules: {
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      loading2: false,
      rules: {
        order_status: [
          { required: true, message: "请选择状态", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      isSubmitLoading: false,
      dialogConfig,
      checkList: [],
      curItem: {},
      form: {},
      open: false,
      loading2: false,
      showSearch: true,
      isShowDialog: false,
      isLoading: false,
      propList,
      formItems,
      info: {},
      searchInfo: {
        pageNum: 1,
        pageSize: 10,
        created_at: this.getTimeFilterDefault(true),
      },
      title2: "",
      open2: false,
      form2: {},
      rules2: {
        change_channel: [
          { required: true, message: "请选择是否变更渠道", trigger: "blur" },
        ],
        channel_id: [
          {
            required: true,
            message: "请选择渠道",
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      act: 0,
      channelList: [],
      openRefund: false,
      multiple: true,
      ids: [],
    };
  },
  computed: {},
  created() {
    sendThis(this);
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      this.getInfo();
      this.getProvinceList();
      this.getPayAllList();

      // this.getAllSpec();
      this.getChannelList();
      this.getAllCateList();
    },
    async getPayAllList() {
      const { data } = await getPayAllList();
      // 赋值表单数据
      this.formItems.forEach((item) => {
        if (item.prop == "payment_id") {
          item.options = data;
        }
      });
    },
    async getAllCateList() {
      const { data } = await getAllCateList();
      // 赋值表单数据
      // this.dialogConfig.formConfig.formItems.forEach((item) => {
      //   if (item.prop == "cate_id") {
      //     item.options = data;
      //   }
      // });
      this.formItems.forEach((item) => {
        if (item.prop == "cate_id") {
          item.options = data;
        }
      });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleRefund() {
      this.formRefund = {
        remark: undefined,
        password: undefined,
      };
      this.resetForm("formRefund");
      this.openRefund = true;
    },
    getChannelList() {
      listAllChannel().then((response) => {
        this.channelList = response.data;
      });
    },
    getCityList(id, formItems) {
      getAreas({ level_type: 2, parent_id: id }).then((response) => {
        // this.cityList = response.data;
        formItems.forEach((item) => {
          if (item.prop == "city_id") {
            item.options = response.data;
          }
        });
      });
    },
    async getAllSpec() {
      const { data } = await getAllSpec();
      this.formItems.forEach((item) => {
        if (item.prop == "spec_id") {
          item.options = data;
        }
      });
    },
    async getInfo() {
      this.isLoading = true;
      const params = { ...this.searchInfo };
      const { data } = await getList(params);
      console.log(data);
      this.info = data;
      this.isLoading = false;
    },
    reset() {
      this.form = {
        order_status: undefined,
        is_callback: undefined,
        remark: undefined,
        password: undefined,
      };
      this.resetForm("form");
    },
    orderResubmit() {
      this.reset2();
      this.title2 = "重提订单";
      this.open2 = true;
      return;
    },
    reset2() {
      this.act = 0;
      this.form2 = {
        change_channel: undefined,
        password: undefined,
        channel_id: undefined,
      };
      this.resetForm("form2");
    },
    //压单重提
    submitForm2() {
      this.loading2 = true;
      const ids = this.checkList.map((item) => item.id) || [];
      this.$refs["form2"].validate((valid) => {
        if (valid) {
          orderReSubmit({ ...this.form2, ids })
            .then((res) => {
              this.getInfo();
              this.$modal.msgSuccess("操作成功");
              this.open2 = false;
            })
            .finally(() => {
              this.loading2 = false;
            });
        } else {
          this.loading2 = false;
        }
      });
    },
    changeAuto(type) {
      this.loading = true;
      const ids = this.checkList.map((item) => item.id) || [];
      this.$modal
        .confirm(
          "确认要改变处理方式为：[" +
            (type == 1 ? "自动" : "手动") +
            "处理] 吗？"
        )
        .then(function () {
          return updateOrderProcessType({ ids, type });
        })
        .then(() => {
          this.getInfo();
          this.$modal.msgSuccess("操作成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    changeStatus() {
      this.reset();
      this.open = true;
    },
    submitForm: function () {
      this.loading2 = true;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const orderIds = this.checkList.map((item) => item.id) || [];
          changeStatus({ ...this.form, ids: orderIds })
            .then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getInfo();
            })
            .finally(() => {
              this.loading2 = false;
            });
        } else {
          this.loading2 = false;
        }
      });
    },
    exportOrder() {
      // 导出勾选的订单
      // const orderIds = this.ids || [];
      const orderIds = this.checkList.map((item) => item.id) || [];
      console.log(orderIds);
      if (orderIds.length) {
        this.download(
          "member/order/exportUserOrderList",
          { ids: orderIds },
          "商户订单导出[" + this.parseTime(new Date().getTime()) + "].csv"
        );
      } else {
        const obj = { ...this.searchInfo };
        // obj.created_at = [obj.params.beginTime, obj.params.endTime];
        // delete obj.params;
        this.download(
          "member/order/exportUserOrderList",
          obj,
          "商户订单导出[" + this.parseTime(new Date().getTime()) + "].csv"
        );
      }
    },
    getProvinceList() {
      getArea({ level_type: 1 }).then((response) => {
        this.formItems.forEach((item) => {
          if (item.prop == "province_id") {
            item.options = response.data;
          }
        });
      });
    },
    getCityList(id, formItems) {
      this.searchInfo.city_id = null;
      getArea({ level_type: 2, parent_id: id }).then((response) => {
        formItems.forEach((item) => {
          if (item.prop == "city_id") {
            item.options = response.data;
          }
        });
      });
    },
    selectionChange(e) {
      console.log(e);
      this.checkList = e;
    },
    resetSearch() {
      this.searchInfo = this.$options.data.call(this).searchInfo;
      this.searchInfo.created_at = this.getTimeFilterDefault(true);
      this.getInfo();
    },
    submit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          this.isSubmitLoading = true;
          try {
            await refund(this.dialogConfig.formConfig.formData);
            this.$message.success("操作成功");
            this.isShowDialog = false;
            this.getInfo();
          } finally {
            this.isSubmitLoading = false;
          }
        }
      });
    },
    refund(item) {
      if (item) {
        // 点击退款按钮
        this.isShowDialog = true;
        this.dialogConfig.formConfig.formData = { ...item };
        // this.$modal
        //   .confirm("确定要退款吗？")
        //   .then(function () {
        //     return refund(item.id);
        //   })
        //   .then(() => {
        //     this.getInfo();
        //     this.$modal.msgSuccess("操作成功");
        //   })
        //   .catch(() => {});
      } else {
        // const ids = this.checkList.map((i) => i.id);
        // this.$modal
        //   .confirm("选中" + ids.length + "个,确定要批量退款吗？")
        //   .then(function () {
        //     return refund(ids);
        //   })
        //   .then(() => {
        //     this.getInfo();
        //     this.$modal.msgSuccess("操作成功");
        //   })
        //   .catch(() => {});
      }
    },
    goSearch() {
      // 重置时间
      this.getInfo();
    },
    change(item) {
      // 修改
    },
    del(item) {
      // 删除
    },
  },
};
</script>

<style lang="scss" scoped>
/* .demo-table-expand {
  padding: 0 10px;
  font-size: 0;
}
.demo-table-expand label {
  width: 150px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 60px;
  margin-bottom: 0;
  
} */
.demo-table-expand {
  padding: 0 10px;
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 33.3%;
}
</style>
